# -*- coding : utf-8 -*-

import time
import urllib
from gluon.utils import md5_hash as md5

class TaobaoApi(object):
    ISOTIMEFORMAT= '%Y-%m-%d %X'

    def __init__(self):
        pass

    def now_time(self):
        stime = None
        if(time.timezone == 0):
            gmtimefix = 28800
            stime = time.gmtime(gmtimefix + time.time())
        else:
            stime = time.localtime()
        strtime = time.strftime(self.ISOTIMEFORMAT, stime)
        return strtime

    def db_config_select(self,name):
        my_taobao_config = db(db.config.name == name).select()
        my_taobao_config = my_taobao_config[0]
        return my_taobao_config

    def sip_dict_all(self,vars):
        redirect_url = HOST + '/' + request.application + '/' + request.controller + '/' + request.function + '?' + request.env['query_string']
        sip_dict = {}
        my_taobao_config = self.db_config_select('sip')
#        sip_dict['sip_apiname'] = 'alisoft.validateAppUser'
#        sip_dict['sip_apiname'] = 'taobao.trades.bought.get'
        sip_dict['sip_apiname'] = 'alisoft.fi.account.getDetailAccounts'
        sip_dict['sip_timestamp'] = self.now_time()
        sip_dict['sip_appkey'] = my_taobao_config.appkey
        sip_dict['format'] = 'josn'
#        sip_dict['sip_usertoke'] = 'abc' #?
        sip_dict['v'] = my_taobao_config.v
        sip_dict['sip_sessionid'] = response.session_id
        sip_dict['sip_redirecturl'] = redirect_url
        sip_dict['nicks'] = 'tel800810'
        sip_dict['fields'] = 'title' #'id,nick,created,location.city'
        sip_dict.update(vars)
        return sip_dict

    def sip_sign(self,list,dict):
        temp_dict = dict
        my_taobao_config = self.db_config_select('sip')
        cert_code = my_taobao_config.secret
        keys_list = []
        for i in list:
            keys_list.append(i)
        keys_list.sort()
        sip_sign = ''
        for i in keys_list:
            sip_sign += i
            sip_sign += str(temp_dict[i])
        sip_sign = cert_code + sip_sign
        sip_sign = md5(sip_sign)
        return sip_sign

    def sip_url(self,list,sip_dict):
        import copy
        url = ''
        temp_dict = copy.deepcopy(sip_dict)
        temp_dict['sip_timestamp'] = urllib.quote_plus(temp_dict['sip_timestamp'])
        for i in list:
            url += '%s=%s&' % (i, str(temp_dict[i]))
#            url += '%s=%s&' % (i, str(sip_dict[i]))
        return url
#        return urllib.quote_plus(url)

    def get_url(self,keys_list,sip_dict,SIP_URL=SIPRESTURL,sip_sign=True):
        sip_url = self.sip_url(keys_list, sip_dict)
        sip_url = SIP_URL + '?' + sip_url
        if sip_sign:
            sip_sign = self.sip_sign(keys_list, sip_dict)
            sip_url = sip_url + 'sip_sign=' + sip_sign
        return sip_url


def fetch(url):
    try:
        from google.appengine.api.urlfetch import fetch
        return fetch(url).content
    except:
        import urllib
        return urllib.urlopen(url).read()

taobao_api = TaobaoApi()
login_keys_list = 'sip_appkey', 'sip_apiname', 'sip_sessionid', 'sip_redirecturl'
start_keys_list = 'sip_appkey', 'sip_apiname', 'sip_timestamp', 'userId', 'appId', 'appInstanceId', 'sip_sessionid', 'v', 'fields'#,'format'
common_keys_list = 'sip_appkey', 'sip_apiname', 'sip_timestamp', 'fields', 'sip_sessionid', 'v', 'nicks'#, 'format', 'token'

all_keys_list = {
    'alisoft':['app_instance_id', 'token', 'user_id', 'app_id', 'target'],
    }

#interface =

